package com.erp.erp_servers.Email.Impl;

import com.erp.erp_entitys.Email.email_Pop3;
import com.erp.erp_entitys.Email.email_email;
import com.erp.erp_servers.Email.EmailService;
import com.sun.mail.imap.IMAPFolder;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Store;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

//连接器对象
public class ServicerLink implements Serializable {
    private TreeMap<Integer, Store> stores=new TreeMap<>();
    private TreeMap<Integer, Folder> folders=new TreeMap<>();
    private TreeMap<Integer, Folder> Sendsfolders=new TreeMap<>();
    private TreeMap<Integer, email_email> emails=new TreeMap<>();
    private EmailService eService=null;
    public Folder openFolder(email_Pop3 pop,String READ){
        Store store =null;
        Folder folder=null;
        //如果已经有folder，判断是否可用，可用就用，不可用重新连接获取。这里多次连接会导致报login errer
        if(READ.equals("INBOX")){
            if(folders.containsKey(pop.getPop3_id())){
                folder=folders.get(pop.getPop3_id());
                try {
                    if(folder.exists()==true){
                        if(folder.isOpen()==false){
                            folder.open(Folder.READ_WRITE);
                        }else{
                            try{
                                folder.close(true);
                                folder.open(Folder.READ_WRITE);}
                            catch (Exception e){
                                System.out.println("folder打开失败"+e);
                            }
                        }
                        return folder;
                    }else{
                        folders.remove(pop.getPop3_id());
                        return openFolder(pop,READ);
                    }
                }catch (Exception e){
                    folders.remove(pop.getPop3_id());
                    return openFolder(pop,READ);
                }
            }else {
                for (int i = 0; i < 3; i++) {
                    try {
                        store = getStore(pop, eService);
                        folder = store.getFolder("INBOX");//获取收件箱
                        folder.open(Folder.READ_WRITE); // 设置对邮件帐户的访问权限
                        folders.put(pop.getPop3_id(), folder);
                        break;
                    } catch (Exception e) {
                    }
                }
                return folder;
            }
        }else if(READ.equals("已发送")){
            if(Sendsfolders.containsKey(pop.getPop3_id())){
                folder=Sendsfolders.get(pop.getPop3_id());
                try {
                    if(folder.exists()==true){
                        if(folder.isOpen()==false){
                            folder.open(Folder.READ_WRITE);
                        }else{
                            try{
                                folder.close(true);
                                folder.open(Folder.READ_WRITE);}
                            catch (Exception e){
                                System.out.println("folder打开失败"+e);
                            }
                        }
                        return folder;
                    }else{
                        Sendsfolders.remove(pop.getPop3_id());
                        return openFolder(pop,READ);
                    }
                }catch (Exception e){
                    Sendsfolders.remove(pop.getPop3_id());
                    return openFolder(pop,READ);
                }
            }else {
                for (int i = 0; i < 3; i++) {
                    try {
                        store = getStore(pop, eService);
                        folder = store.getFolder("已发送");//获取收件箱
                        folder.open(Folder.READ_WRITE); // 设置对邮件帐户的访问权限
                        Sendsfolders.put(pop.getPop3_id(), folder);
                        break;
                    } catch (Exception e) {
                    }
                }
                return folder;
            }
        }else{
            return null;
        }

    }

    //新增连接器
    public boolean addLink(email_Pop3 pop3, EmailService emailService)  {
        eService=emailService;
        if(stores.containsKey(pop3.getPop3_id())==false){
            Store store = ServerciEmailUnit.getStore(pop3,emailService);
            if(store!=null){
                stores.put(pop3.getPop3_id(),store);
                return true;
            }
        }
        return false;
    }

    //删除连接池
    public boolean deleteLink(email_Pop3 pop3) throws MessagingException {
        if(stores.containsKey(pop3.getPop3_id())){
            Store store = stores.get(pop3.getPop3_id());
//            Folder folder = folders.get(pop3.getPop3_id());
            store.close();
//            folder.close();
        }else{
            return false;
        }
        return true;
    }

    //获取连接器
    public synchronized Store getStore(email_Pop3 pop3, EmailService emailService) throws MessagingException {
        Store store=null;
        if(stores.containsKey(pop3.getPop3_id())){
            if(stores.get(pop3.getPop3_id()).isConnected()){
                store = stores.get(pop3.getPop3_id());
            }else{
                try{
                    stores.get(pop3.getPop3_id()).close();
                }catch (Exception e){}
                stores.remove(pop3.getPop3_id());
                addLink(pop3,emailService);
                store=stores.get(pop3.getPop3_id());
            }
            return store;
        }else{
            addLink(pop3,emailService);
           return stores.get(pop3.getPop3_id());
        }

    }
    //获取收件箱
    public Folder getFolder(email_Pop3 pop3,String READ)  {
        //可能丢失连接
        Folder folder=null;
        folder = openFolder(pop3,READ);
        return folder;

    }

    //关闭所有连接池
    public void closeAll() throws MessagingException {
        try{
            while(stores.size()==0){
                Map.Entry<Integer, Store> entry = stores.lastEntry();
                entry.getValue().close();
                stores.remove(entry.getKey());
            }

        }catch (Exception e){
            System.out.println("剩余stores为"+stores.size());
        }finally {
            stores.clear();
        }
    }
    //关闭单个连接
    public void closeOne(email_Pop3 pop) throws MessagingException {
        Store store = stores.get(pop.getPop3_id());
        store.close();
    }

    //新增邮件单个
    public boolean addEmail(email_email email){
       if( emails.containsKey(email.getEmail_id())==false){
           emails.put(email.getEmail_id(),email);
           return true;
       }else{
           return false;
       }
    }
    //新增集合
    public void addEmail(List<email_email> emails){
        for(email_email email:emails){
            addEmail(email);
        }
    }

    //删除邮件
    public boolean deleteEmail(email_email email){
        if(emails.containsKey(email.getEmail_id())){
            emails.remove(email.getEmail_id());
            return true;
        }else{
            return false;
        }
    }
    //清空邮件
    public boolean deleteAlLEmail(){
        boolean re=false;
        try {
            if(this.emails.size()>0){
                emails.clear();
            }
            re=true;
        }catch (Exception e){
            re=false;
        }
        return re;
    }
    public email_email getRamEmail(){
        if(emails.size()>0){
            return emails.lastEntry().getValue();
        }else{
            return null;
        }

    }
    public int getEmailSize(){
        return emails.size();
    }
}
